package com.southwind.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.southwind.common.Cache;
import com.southwind.common.ResultObj;
import com.southwind.entity.Admin;
import com.southwind.form.RuleForm;
import com.southwind.service.AdminService;
import com.wf.captcha.SpecCaptcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedirectController {

    @Autowired
    private AdminService adminService;

    @GetMapping("/getCode")
    public String getCode(){
        SpecCaptcha captcha = new SpecCaptcha(130,48,4);
        String code = captcha.text().toLowerCase();
        Cache.map.put("code", code);
        return captcha.toBase64();
    }

    @GetMapping("/login")
    public ResultObj login(RuleForm ruleForm){
        QueryWrapper<Admin> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("admin_account", ruleForm.getLoginname());
        Admin admin = this.adminService.getOne(queryWrapper);
        if(admin == null) return ResultObj.LOGIN_ERROR_LOGINNAME;
        if(!admin.getAdminPassword().equals(ruleForm.getPassword())) return ResultObj.LOGIN_ERROR_PASSWORD;
        String code = (String) Cache.map.get("code");
        if(!code.equals(ruleForm.getCode())) return ResultObj.LOGIN_ERROR_CODE;
        ResultObj.LOGIN_SUCCESS.setUser(admin);
        return ResultObj.LOGIN_SUCCESS;
    }

}
